import { useEffect, useRef, useState } from 'react';
import { ContainerStyle } from './style';
import { useWebSocket } from 'ahooks';
import { userInfo } from './config';
import jsonbig from 'json-bigint';
import GroupList, { type GroupListRef } from './c-cpns/GroupList';
import ChatContainer, { type ChatContentRef } from './c-cpns/ChatContainer';
import type { GroupRes } from './http/chatting-group';
import type { RecordsRes } from './http/chatting-records';

// socket返回类型
export interface IWSData {
	msgType: number;
	toUser: number;
	message: RecordsRes;
}

const BetterChat = () => {
	const [activeGroup, setActiveGroup] = useState<GroupRes>();
	const ChatRef = useRef<ChatContentRef>();
	const GroupRef = useRef<GroupListRef>();

	// webSocket 相关
	const { disconnect, latestMessage } = useWebSocket(
		`ws://dev-host/api/notice/message/websocket/${userInfo.id}`,
		{
			reconnectLimit: 5,
			reconnectInterval: 5000
		}
	);

	// 刷新群列表信息
	const refreshGroupList = () => GroupRef.current?.refreshGroupList();

	useEffect(() => {
		if (latestMessage) {
			const data = jsonbig({ storeAsString: true }).parse(latestMessage.data) as IWSData;
			if (data.msgType === 11) {
				// 添加新消息
				ChatRef.current?.refreshNewMsg(data);
				// 刷新群列表
				refreshGroupList();
			}
		}
	}, [latestMessage]);

	useEffect(() => {
		return () => {
			// 断开socket
			disconnect();
		};
	}, []);

	return (
		<ContainerStyle>
			{/* 最左侧菜单切换 */}
			{/* <Toolbar /> */}
			{/* 群、用户列表 */}
			<GroupList groupRef={GroupRef} setActiveGroup={setActiveGroup} />
			{/* 聊天区 */}
			<ChatContainer
				charRef={ChatRef}
				active={activeGroup}
				refreshGroupList={refreshGroupList}
				onDelGroup={() => GroupRef.current?.resetActive()}
			/>
		</ContainerStyle>
	);
};

export default BetterChat;
